"use strict"

var amqp = require('amqplib/callback_api');
var ProtoBuf = require('protobufjs');

var builder = ProtoBuf.loadProtoFile("./person.proto")
var Test = builder.build('Test'); // namespace package Test
var Person = Test.Person;

var wzqJson = {
	"name": "加入的项目组",
	"age": 32,
	"id": 101,
	"addr": "cn"
};
var wzq = new Person(wzqJson);
var buffer = wzq.toBuffer();
var buflen = buffer.length;

amqp.connect('amqp://localhost', function(err, conn) {
	if (err) return console.error('connect error ', err);
	conn.createChannel(function(err, ch) {
		if (err) return console.err('createChannel error ', err);

		var ex = 'rpc_exchange';
		var q_A2B = 'q_A2B';
		var key_A2B = 'key_A2B';

		var q_B2A = 'q_B2A'
		var key_B2A = 'key_B2A';
		ch.assertExchange(ex, 'topic', {
			durable: true
		});
		ch.prefetch(1);

		ch.assertQueue(q_A2B, {
			exclusive: false
		}, function(err, q1) {
			ch.assertQueue(q_B2A, {
				exclusive: false
			}, function(err, q2) {
				ch.bindQueue(q_A2B, ex, key_A2B);
				ch.bindQueue(q_B2A, ex, key_B2A);

				// send
				var msgPattern = 'hello,i from appA, id=';
				var count = 0;
				var msgSend;
				setInterval(function() {
					msgSend = msgPattern + count;
					count++;
					console.log(' [s] appA send %s, buflen=%s', msgSend, buflen);
					ch.publish(ex, key_A2B, buffer);
				}, 2000);
			});
		})
	});
});